package com.gtmc.gclub.chat.jmessage;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gtmc.gclub.chat.bean.Result;
import com.gtmc.gclub.chat.constants.ChatConstant;
import com.gtmc.gclub.chat.constants.CommonProperties;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jmessage.api.common.model.RegisterInfo;
import cn.jmessage.api.user.UserClient;
import cn.jmessage.api.user.UserInfoResult;
import cn.jmessage.api.user.UserStateResult;

@Component(value = "userOperator")
public class UserOperator {
	private static Logger log = LoggerFactory.getLogger(UserOperator.class);

	@Autowired
	private CommonProperties commonProperties;

	// 是否可以使用一个client ？
	// @Autowired
	// private static JMessageClient client = new
	// JMessageClient(commonProperties.getAppkey(),
	// commonProperties.getMasterSecret());


public static void main(String[] args) {
	UserOperator entity = new UserOperator();
	String appKey = "2da93a099ef98d054aeb585a";
	String secret = "93a7cdc961dc2cbd2c0b0ab4";
	String username = "testRepart" ;
	String password = "123456";
	UserClient client = new UserClient(appKey, secret);
	Result<Map> rtn = null;
	try {
		RegisterInfo user = RegisterInfo.newBuilder().setUsername(username).setPassword(password).build();
		ResponseWrapper res = client.registerAdmins(user);
		log.debug("Res status: " + res.responseCode);
		log.debug("Res content: " + res.responseContent);
		if (res.responseCode == ChatConstant.RESPONSE_CODE_CREATE_SUC) {
			rtn = new Result<Map>(1, null, null);
		} else {
			rtn = new Result<Map>(0, null, String.valueOf(res.responseCode));
		}
	} catch (APIConnectionException e) {
		log.error("Connection error. Should retry later. ", e);
    	rtn = new Result<Map>(ChatConstant.RESULT_RETURN_FLAG_CONNECTION, null, null);
	} catch (APIRequestException e) {
		log.error("Error response from JPush server. Should review and fix it. ", e);
		log.info("HTTP Status: " + e.getStatus());
		log.info("Error Message: " + e.getMessage());
		JSONObject obj = new JSONObject(e.getMessage());
		JSONObject error = obj.optJSONObject("error");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", error.optInt("code"));
		map.put("message", error.optString("message"));
		if(error.optInt("code") == ChatConstant.SERVER_ERRORCODE_USER_EXIST){ // 唉！ wuqi
			rtn = new Result<Map>(1, map, String.valueOf(e.getStatus()));
		}else{
			rtn = new Result<Map>(0, map, String.valueOf(e.getStatus()));
		}
		
	}
	System.out.println(rtn);
}
	/**
	 * 注册jmessage管理员
	 * 
	 * @param userName
	 *            用户名
	 * @param password
	 *            用户密码
	 * @return Result<Map> returnFlag: 1 成功 0失败 
	 * 							 data： Map，错误内容 errorMsg：
	 *         							   http返回code
	 */
	public Result<Map> registerAdmins(String userName, String password) {
		log.debug("Jmessage regAdmin : " + userName + " " + password);
		UserClient client = new UserClient(commonProperties.getAppkey(), commonProperties.getMasterSecret());
		Result<Map> rtn = null;
		try {
			RegisterInfo user = RegisterInfo.newBuilder().setUsername(userName).setPassword(password).build();

			// JsonObject obj = new JsonObject();

			ResponseWrapper res = client.registerAdmins(user);
			log.debug("Res status: " + res.responseCode);
			log.debug("Res content: " + res.responseContent);
			if (res.responseCode == ChatConstant.RESPONSE_CODE_CREATE_SUC) {
				rtn = new Result<Map>(1, null, null);
			} else {
				rtn = new Result<Map>(0, null, String.valueOf(res.responseCode));
			}

		} catch (APIConnectionException e) {
			log.error("Connection error. Should retry later. ", e);
        	rtn = new Result<Map>(ChatConstant.RESULT_RETURN_FLAG_CONNECTION, null, null);
		} catch (APIRequestException e) {
			log.error("Error response from JPush server. Should review and fix it. ", e);
			log.info("HTTP Status: " + e.getStatus());
			log.info("Error Message: " + e.getMessage());
			JSONObject obj = new JSONObject(e.getMessage());
			JSONObject error = obj.optJSONObject("error");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", error.optInt("code"));
			map.put("message", error.optString("message"));
			if(error.optInt("code") == ChatConstant.SERVER_ERRORCODE_USER_EXIST){ // 唉！ wuqi
				rtn = new Result<Map>(1, map, String.valueOf(e.getStatus()));
			}else{
				rtn = new Result<Map>(0, map, String.valueOf(e.getStatus()));
			}
			
		}
		return rtn;
	}

	
	/**
	 * 获取jmessage账号信息
	 * @param userName  在JMessage账号
	 * 
	 * @return Result<Map>
	 */
    public  Result<Map> getUserInfo(String userName) {
    	log.debug("Jmessage getUserInfo : " + userName );
        UserClient client = new UserClient(commonProperties.getAppkey(), commonProperties.getMasterSecret());
        Result<Map> rtn = null;
        try {
            UserInfoResult res = client.getUserInfo(userName);
            

			Map<String, Object> map = new HashMap<String, Object>();
			if(res.getUsername() != null){
				map.put("username", res.getUsername());
			}
			if(res.getNickname() != null){
				map.put("nickname", res.getNickname());
			}
			if(res.getAvatar() != null){
				map.put("avatar", res.getAvatar());
			}
			if(res.getBirthday() != null){
				map.put("birthday", res.getBirthday());
			}
			if(res.getGender() != null){
				map.put("gender", res.getGender());
			}
			if(res.getSignature() != null){
				map.put("signature", res.getSignature());
			}
			if(res.getRegion() != null){
				map.put("region", res.getRegion());
			}			
			if(res.getAddress() != null){
				map.put("address", res.getAddress());
			}			
			if(res.getMtime() != null){
				map.put("mtime", res.getMtime());
			}			
			if(res.getCtime() != null){
				map.put("ctime", res.getCtime());
			}			

			log.info(res.toString());
			rtn = new Result<Map>(1, map, null);
        } catch (APIConnectionException e) {
        	log.error("Connection error. Should retry later. ", e);
           	rtn = new Result<Map>(ChatConstant.RESULT_RETURN_FLAG_CONNECTION, null, null);
        } catch (APIRequestException e) {
        	log.error("Error response from JPush server. Should review and fix it. ", e);
        	log.info("HTTP Status: " + e.getStatus());
        	log.info("Error Message: " + e.getMessage());
			JSONObject obj = new JSONObject(e.getMessage());
			JSONObject error = obj.optJSONObject("error");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", error.optInt("code"));
			map.put("message", error.optString("message"));
			rtn = new Result<Map>(0, map, String.valueOf(e.getStatus()));
        }
        return rtn;
    }
    
	/**
	 * 获取jmessage用户是否在线信息
	 * @param userName  在JMessage账号
	 * 
	 * @return Result<Map>
	 */
    public Result<Map> getUserState(String userName) {
    	log.debug("Jmessage getUserState : " + userName );
    	UserClient client = new UserClient(commonProperties.getAppkey(), commonProperties.getMasterSecret());
    	Result<Map> rtn = null;
        try {
        	UserStateResult res = client.getUserState(userName);
        	Map<String, Object> map = new HashMap<String, Object>();
			if(res.getLogin() != null){
				map.put("login", res.getLogin());
			}
			if(res.getOnline() != null){
				map.put("online", res.getOnline());
			}
			log.info(res.toString());
			rtn = new Result<Map>(1, map, null);			
        } catch (APIConnectionException e) {
        	log.error("Connection error. Should retry later. ", e);
           	rtn = new Result<Map>(ChatConstant.RESULT_RETURN_FLAG_CONNECTION, null, null);
        } catch (APIRequestException e) {
        	log.error("Error response from JPush server. Should review and fix it. ", e);
        	log.info("HTTP Status: " + e.getStatus());
        	log.info("Error Message: " + e.getMessage());
			JSONObject obj = new JSONObject(e.getMessage());
			JSONObject error = obj.optJSONObject("error");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", error.optInt("code"));
			map.put("message", error.optString("message"));
			rtn = new Result<Map>(0, map, String.valueOf(e.getStatus()));
       }
        
        return rtn;
    }  
    
//    public  Result<Map> updateUserInfo(String userName,) {
//        //JMessageClient client = new JMessageClient(appkey, masterSecret);
//        log.debug("Jmessage updateUserInfo : ");
//    	UserClient client = new UserClient(commonProperties.getAppkey(), commonProperties.getMasterSecret());
//    	Result<Map> rtn = null;
//        
//        try {
//            client.updateUserInfo("test_user", "test_nick", "2000-01-12", "help me!", 1, "shenzhen", "nanshan");
//        } catch (APIConnectionException e) {
//            LOG.error("Connection error. Should retry later. ", e);
//        } catch (APIRequestException e) {
//            LOG.error("Error response from JPush server. Should review and fix it. ", e);
//            LOG.info("HTTP Status: " + e.getStatus());
//            LOG.info("Error Message: " + e.getMessage());
//        }
//        return rtn;
//    }
}
